<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <!-- 搜索表单 -->
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="3" style="padding-bottom: 2px;max-width: 250px">
              <v-text-field
                label="表名称"
                v-model="queryParams.tableName"
                placeholder="请输入表名称"
                outlined
                dense
                clearable
                hide-details="auto"
                @keyup.enter.native="handleQuery"
                style="width: 250px;"
              ></v-text-field>
            </v-col>
            <v-col md="3" style="padding-bottom: 2px;max-width: 250px">
              <v-text-field
                label="表描述"
                v-model="queryParams.tableComment"
                placeholder="请输入表描述"
                outlined
                dense
                hide-details="auto"
                style="width: 250px;"
                @keyup.enter.native="handleQuery"
              ></v-text-field>

            </v-col>
            <v-col cols="12" sm="6" md="2" style="padding-bottom: 2px;max-width: 180px">
              <v-menu
                ref="dateRangeMenu"
                v-model="dateRangeMenu"
                :close-on-content-click="false"
                transition="scale-transition"
                offset-y
                max-width="240px"
                min-width="auto"
                hide-details="auto"
                style="width: 240px;padding-top: 0;margin-top: 0"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="date"
                    label="创建时间"
                    prepend-icon="mdi-calendar"
                    v-bind="attrs"
                    @blur="date = parseDate(dateFormatted)"
                    v-on="on"
                    clearable
                    style="width: 240px;padding-top: 0"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="date"
                  no-title
                  @input="dateRangeMenu = false"
                  style="padding: 0"
                ></v-date-picker>
              </v-menu>
            </v-col>
            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>

    <!-- 表格操作按钮区 -->
    <v-row style="margin-bottom: -5px;margin-top: 0;">
      <!--二次确认删除按钮 -->
      <v-col md="1" style="max-width: 84px">
        <v-btn color="primary"
               small
               plain
               outlined
               :disabled="multiple"
               @click="handleGenTable()"
               v-hasPermi="['tool:gen:code']">
          <v-icon left>
            mdi-hammer
          </v-icon>
          生成
        </v-btn>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn
          type="success"
          small
          plain
          outlined
          @click="openImportTable"
          v-hasPermi="['tool:gen:import']">
          <v-icon left>
            mdi-download
          </v-icon>
          导入
        </v-btn>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn color="success"
          small
          plain
          outlined
          :disabled="single"
          @click="handleEditTable(ids[0])"
          v-hasPermi="['tool:gen:edit']">
          <v-icon left>
            mdi-pencil
          </v-icon>
          修改
        </v-btn>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <span v-if="!showConfirmDelete">
          <v-btn color="#C62828"
                 small
                 plain
                 outlined
                 :disabled="multiple"
                 @click="onClickDelete()"
                 v-hasPermi="['tool:gen:remove']">
            <v-icon left>
              mdi-delete
            </v-icon>
            删除
          </v-btn>
        </span>
        <span v-else>
          <v-tooltip top style="z-index: 1000">
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                small color="error"
                plain
                outlined
                :disabled="multiple"
                v-bind="attrs"
                v-on="on"
                @click="handleDelete()"
                v-hasPermi="['tool:gen:remove']">
                <v-icon left>
                  mdi-delete
                </v-icon>
                确定
              </v-btn>
            </template>
            <span>请再次点击确定删除</span>
          </v-tooltip>
        </span>
      </v-col>
      <v-col style="float: right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </v-col>
    </v-row>

    <v-main>
      <v-data-table v-if="tableList"
                    v-model="ids"
                    :headers="headers"
                    :items="tableList"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="tableId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >
        <!-- 序号 -->
        <template v-slot:item.index="{ item, index }">
          {{ index + 1}}
        </template>
        <!-- 按钮插槽 -->
        <template v-slot:item.actions="{ item, index }">
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handlePreview(item, index)"
                 v-hasPermi="['tool:gen:preview']">
            <v-icon small>
              mdi-eye
            </v-icon>
            预览
          </v-btn>
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handleEditTable(item)"
                 v-hasPermi="['tool:gen:edit']">
            <v-icon small>
              mdi-pencil
            </v-icon>
            编辑
          </v-btn>
          <!-- 删除确认 -->
          <span v-if="item && !item.showConfirmDelete">
            <v-btn color="#C62828"
                   small
                   plain
                   height="20"
                   width="40"
                   @click="onClickTableDelete(item)">
              <v-icon small>
                mdi-delete
              </v-icon>
              删除
            </v-btn>
          </span>
          <span v-else>
            <v-tooltip top>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  small color="error"
                  plain
                  height="20"
                  width="40"
                  v-bind="attrs"
                  v-on="on"
                  @click="handleDelete(item)"
                  v-hasPermi="['tool:gen:remove']">
                  <v-icon small>
                    mdi-delete
                  </v-icon>
                  确定
                </v-btn>
              </template>
              <span>请再次点击确定删除</span>
            </v-tooltip>
          </span>
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 :disabled="warnVisible"
                 @click="clickSynchDb(item)"
                 v-hasPermi="['tool:gen:edit']">
            <v-icon small>
              mdi-cached
            </v-icon>
            同步
          </v-btn>
          <v-btn text color="primary"
                 small
                 plain
                 height="20"
                 width="80"
                 @click="handleGenTable(item)"
                 v-hasPermi="['tool:gen:code']">
            <v-icon small>
              mdi-hammer
            </v-icon>
            生成代码
          </v-btn>
        </template>
      </v-data-table>
      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <v-row justify="center">
      <v-dialog
        v-model="warnVisible"
        max-width="40%" width="auto"
      >
        <v-card>
          <v-card-title class="text-h6" style="padding-bottom: 5px !important;">
            确认要强制同步 {{ form.tableName }} 表结构吗?
          </v-card-title>
          <!-- 按钮 -->
          <v-card-actions style="padding-top: 0">
            <v-spacer></v-spacer>
            <v-btn
              color="green darken-1"
              text
              @click="warnVisible = false;form = {};"
            >
              取消
            </v-btn>
            <v-btn
              color="darken-1"
              text
              @click="handleSynchDb()"
            >
              确定
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>

    <!-- 预览界面 -->
    <v-dialog v-model="preview.open"
              transition="dialog-top-transition"
              style="z-index: 10001" max-width="80%">

      <v-card style="padding: 12px 0 12px 12px;border-top-left-radius: 0;border-top-right-radius: 0">
        <!-- 对话框标题 -->
        <v-card-title>
          <span style="font-size: 18px">代码预览</span>
          <!-- 关闭按钮 -->
          <v-spacer></v-spacer>
          <v-btn
            icon
            class="hidden-xs-only"
            @click="preview.open = false"
          >
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <el-tabs v-model="preview.activeName">
          <el-tab-pane
            v-for="(value, key) in preview.data"
            :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
            :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
            :key="key"
          >
            <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
          </el-tab-pane>
        </el-tabs>
      </v-card>
    </v-dialog>

    <!-- 导入界面 -->
    <import-table ref="import" @ok="handleQuery" />
  </div>
</template>

<script>
import { listTable, previewTable, delTable, genCode, synchDb } from "@/api/tool/gen";
import importTable from "./importTable";
import { downLoadZip } from "@/utils/zipdownload";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import { commonUtils } from "@/utils/commonUtils";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));

export default {
  name: "Gen",
  components: { importTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 唯一标识符
      uniqueId: "",
      // 选中数组
      ids: [],
      // 选中表数组
      tableNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表数据
      tableList: [],
      // 日期范围
      dateRange: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        totalPages: 0, // 总页数
        tableName: undefined,
        tableComment: undefined
      },
      form: {},
      showConfirmDelete: false,
      warnVisible: false,
      previewTab: null,
      previewModel: null,
      // 预览参数
      preview: {
        open: false,
        title: "代码预览",
        data: {},
        activeName: "domain.java"
      },
      headers: [
        {
          text: '序号', value: 'index', align: 'center', sortable: false, width: '70px' },
        { text: '表名称', value: 'tableName', sortable: false, align: 'center', width: '130px' },
        { text: '表描述', value: 'tableComment', sortable: false, align: 'center', width: '130px' },
        { text: '实体', value: 'className', sortable: false, align: 'center' },
        { text: '创建时间', value: 'createTime', sortable: false, align: 'center' },
        { text: '更新时间', value: 'updateTime', sortable: false, align: 'center' },
        { text: '操作', value: 'actions', sortable: false, align: 'center' },
      ],
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      date: null,
      dateRangeMenu: false,
      dateFormatted: commonUtils.formatDate((new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substr(0, 10)),
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    },
    date (val) {
      this.dateFormatted = this.formatDate(this.date)
    },
  },
  created() {
    this.getList();
  },
  activated() {
    const time = this.$route.query.t;
    if (time != null && time != this.uniqueId) {
      this.uniqueId = time;
      this.resetQuery();
    }
  },
  methods: {
    /** 查询表集合 */
    getList() {
      this.loading = true;
      listTable(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.tableList = response.rows;
        this.total = response.total;
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 生成代码操作 */
    handleGenTable(row) {
      const tableNames = row.tableName || this.tableNames;
      if (tableNames == "") {
        this.msgError("请选择要生成的数据");
        return;
      }
      if(row.genType === "1") {
        genCode(row.tableName).then(response => {
          this.msgSuccess("成功生成到自定义路径：" + row.genPath);
        });
      } else {
        downLoadZip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
      }
    },
    clickSynchDb(item) {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      this.form = item;
      this.$nextTick(() => {
        this.warnVisible = true;
      })
    },
    /** 同步数据库操作 */
    async handleSynchDb() {
      const tableName = this.form.tableName;
      await synchDb(tableName).then(() => {
        this.warnVisible = false;
        this.$store.dispatch('snackbar/openSnackbar', {
          msg: '同步成功',
          color: 'success'
        })
      })
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    /** 预览按钮 */
    handlePreview(row) {
      previewTable(row.tableId).then(response => {
        this.preview.data = response.data;
        this.preview.open = true;
      });
    },
    /** 高亮显示 */
    highlightedCode(code, key) {
      const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
      var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
      const result = hljs.highlight(language, code || "", true);
      return result.value || '&nbsp;';
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
      this.tableNames = this.ids.map(item => item.tableName);
      this.showConfirmDelete = false;
    },
    /** 修改按钮操作 */
    handleEditTable(row) {
      const tableId = row.tableId;
      this.$router.push("/gen/edit/" + tableId);
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete() {
      this.showConfirmDelete = true;
      setTimeout(() => {
        this.showConfirmDelete = false;
      }, 4000);
    },
    // 点击行删除
    onClickTableDelete(item) {
      this.$set(item, 'showConfirmDelete', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmDelete', false);
      }, 3500);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const tableIds = row != null ? row.tableId : this.ids.map(item => item.tableId);
      await delTable(tableIds).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '删除成功',
            color: 'success'
          })
          this.getList();
        }
      })
    },
    // 创建时间 日期格式化
    formatDate (date) {
      if (!date) return null
      const [year, month, day] = date.split('-')
      return `${month}/${day}/${year}`
    },
    parseDate (date) {
      if (!date) return null
      const [month, day, year] = date.split('/')
      return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
    },
  }
};
</script>
